package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsAdminStorageService;
import com.qf.util.ResponseUtil;
import com.qf.util.UUID;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YDW
 * projectName:shop-manage
 * time:2022/5/21 16:49
 * description:
 */
@RestController
@RequestMapping("/admin/storage")
public class AdminStorageController {

    @Autowired
    DtsAdminStorageService storageService;


    @RequiresPermissions("admin:storage:list")
    @RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(name = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(name = "limit",required = false,defaultValue = "10") Integer limit,
            String sort,String order, String key,String name
    ){
        IPage<DtsStorage> ipage=storageService.queryPage(page,limit,sort,order,key,name);
        Map<String,Object> data=new HashMap<>();
        data.put("total",ipage.getTotal());
        data.put("items",ipage.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:storage:create")
    @RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "上传")
    @PostMapping("/create")
    public Object create(MultipartFile file) throws Exception {

        //获取文件的字节数组
        byte[] bytes=file.getBytes();

        //生成唯一的文件名
        String uuid= UUID.randomUUID().toString().replaceAll("-","");

        //获得原始文件名
        String name = file.getOriginalFilename();

        //拼接完整文件名
        String key=uuid+name;

        //获取文件大小
        Integer size = Math.toIntExact(file.getSize());

        //获取文件类型
        String type = file.getContentType();
        DtsStorage dtsStorage = storageService.add(bytes, key, name, size, type);


        return  ResponseUtil.ok(dtsStorage);
    }

    @RequiresPermissions("admin:storage:delete")
    @RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage dtsStorage){
        storageService.delete(dtsStorage);
        return ResponseUtil.ok();

    }

    @RequiresPermissions("admin:storage:update")
    @RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage dtsStorage){
        DtsStorage reStorage=storageService.update(dtsStorage);
        return ResponseUtil.ok(reStorage);
    }
}
